package com.cxria.shiro.shiro.realm;

import com.cxria.shiro.entity.Permission;
import com.cxria.shiro.entity.Role;
import com.cxria.shiro.entity.SUser;
import com.cxria.shiro.service.ShiroUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

	@Autowired
	private ShiroUserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		SUser user = userService.getByUsername(username);
		List<Role> roles = user.getRoles();
		Set<String> roleNames = new HashSet<>();
		Set<String> permissions = new HashSet<>();
		for (Role role : roles) {
			if(role.getAvailable()){
				roleNames.add(role.getRoleName());
			}
			List<Permission> permissions1 = role.getPermissions();
			for(Permission authority : permissions1){
				if(authority.getAvailable()){
					permissions.add(authority.getPermissionName());
				}
			}
		}
		authorizationInfo.setRoles(roleNames);
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
		String username = (String) token.getPrincipal();
		//String password = new String((char[]) token.getCredentials());
		SUser user = userService.getByUsername(username);
		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		} else if (user.getLocked()) {
			throw new LockedAccountException(); // 帐号锁定
		}
		// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
		String realmName = getName();
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), // 用户名
				user.getPassword(), // 密码
				ByteSource.Util.bytes(user.getSalt()), // salt=username+salt
				realmName // realm name
		);
		return authenticationInfo;
	}

}
